﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;

namespace Fotobanka
{
    /// <summary>
    /// Obsluzna trida pro praci s fotkama
    /// </summary>
    public class PhotoManager
    {
        SqlConnection connection;
        SqlCommand command;
        SqlDataReader reader;

        /// <summary>
        /// Vlozi fotku do databaze
        /// </summary>
        /// <param name="gallery_id">id galerie</param>
        /// <param name="fUpload">upload souboru</param>
        /// <param name="title">titulek</param>
        public void InsertPhoto(int gallery_id, FileUpload fUpload, string title)
        {
            try
            {
                //tvorba nahledu - http://www.csharp-station.com/Articles/Thumbnails.aspx
                using (connection = new SqlConnection(ConfigurationManager.ConnectionStrings["amalka"].ToString()))
                {
                    System.Drawing.Image image = System.Drawing.Image.FromStream(fUpload.PostedFile.InputStream);
                    DateTime current = DateTime.Now;

                    connection.Open();

                    command = new SqlCommand("INSERT INTO Photos (gallery_id, content_type, file_name, width, height, create_on, update_on, title) VALUES (@gid, @type, @fname, @w, @h, @created, @updated, @title);", connection);
                    command.Parameters.Add(new SqlParameter("@gid", gallery_id));
                    command.Parameters.Add(new SqlParameter("@type", fUpload.PostedFile.ContentType));
                    command.Parameters.Add(new SqlParameter("@fname", Utils.GetMd5Hash(fUpload.PostedFile.FileName + current.ToString())));
                    command.Parameters.Add(new SqlParameter("@w", image.Width));
                    command.Parameters.Add(new SqlParameter("@h", image.Height));
                    command.Parameters.Add(new SqlParameter("@created", DateTime.Now));
                    command.Parameters.Add(new SqlParameter("@updated", DateTime.Now));
                    command.Parameters.Add(new SqlParameter("@title", title));

                    command.ExecuteNonQuery();
                    //ulozime original
                    fUpload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(Utils.FotoFolder + @"\" + Utils.GetMd5Hash(fUpload.PostedFile.FileName + current.ToString())));
                
                    //vytvorime a ulozime nahled
                    System.Drawing.Image thumbnailImage = image.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                    thumbnailImage.Save(HttpContext.Current.Server.MapPath(Utils.FotoFolder + @"\" + Utils.GetMd5Hash(fUpload.PostedFile.FileName + current.ToString()) + Utils.ThumbExtension));
 
                }
            }
            catch (SqlException sqlexc)
            {
                Console.WriteLine(sqlexc.Message);
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }

        /// <summary>
        /// Vlozi fotku do databaze
        /// </summary>
        /// <param name="gallery_id">id galerie</param>
        /// <param name="stream">datovy stream</param>
        /// <param name="title">titulek</param>
        /// <param name="filename">nazev souboru</param>
        public void InsertPhoto(int gallery_id, MemoryStream stream, string title,string filename)
        {
            try
            {
                //tvorba nahledu - http://www.csharp-station.com/Articles/Thumbnails.aspx
                using (connection = new SqlConnection(ConfigurationManager.ConnectionStrings["amalka"].ToString()))
                {
                    System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                    DateTime current = DateTime.Now;

                    connection.Open();

                    command = new SqlCommand("INSERT INTO Photos (gallery_id, content_type, file_name, width, height, create_on, update_on, title) VALUES (@gid, @type, @fname, @w, @h, @created, @updated, @title);", connection);
                    command.Parameters.Add(new SqlParameter("@gid", gallery_id));
                    command.Parameters.Add(new SqlParameter("@type", "image/jpeg"));//nastaven na tvrdo
                    command.Parameters.Add(new SqlParameter("@fname", Utils.GetMd5Hash(filename + current.ToString())));
                    command.Parameters.Add(new SqlParameter("@w", image.Width));
                    command.Parameters.Add(new SqlParameter("@h", image.Height));
                    command.Parameters.Add(new SqlParameter("@created", DateTime.Now));
                    command.Parameters.Add(new SqlParameter("@updated", DateTime.Now));
                    command.Parameters.Add(new SqlParameter("@title", title));

                    command.ExecuteNonQuery();
                    //ulozime original
                    image.Save(HttpContext.Current.Server.MapPath(Utils.FotoFolder + @"\" + Utils.GetMd5Hash(filename + current.ToString())));
                    
                    //vytvorime a ulozime nahled
                    System.Drawing.Image thumbnailImage = image.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                    thumbnailImage.Save(HttpContext.Current.Server.MapPath(Utils.FotoFolder + @"\" + Utils.GetMd5Hash(filename + current.ToString()) + Utils.ThumbExtension));

                }
            }
            catch (SqlException sqlexc)
            {
                Console.WriteLine(sqlexc.Message);
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }

        /// <summary>
        /// ThumbnailCallback
        /// </summary>
        /// <returns>true / false</returns>
        public bool ThumbnailCallback()
        {
            return true;
        }

        /// <summary>
        /// Vyhleda fotky v galerii
        /// </summary>
        /// <param name="gallery_id">id galerie</param>
        /// <returns>seznam fotek</returns>
        public List<PhotoObject> SelectGalleryImages(int gallery_id)
        {
            try
            {
                using (connection = new SqlConnection(ConfigurationManager.ConnectionStrings["amalka"].ToString()))
                {
                    List<PhotoObject> l = new List<PhotoObject>();
                    //prozatim se vybiraji pouze galerie,ktere maji skupiny a v nich je dany uzivatel
                    connection.Open();
                    command = new SqlCommand("SELECT * FROM Photos WHERE gallery_id=@id ", connection);
                    command.Parameters.Add(new SqlParameter("@id", gallery_id));

                    reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        PhotoObject o = new PhotoObject();
                        o.Id = (int)reader["id"];
                        o.ContentType = reader["content_type"].ToString();
                        o.FileName = reader["file_name"].ToString();
                        o.Height = Convert.ToInt32(reader["height"].ToString());
                        o.Width = Convert.ToInt32(reader["width"].ToString());
                        o.Title = reader["title"].ToString();
                        l.Add(o);
                    }

                    return l;

                }
            }
            catch (SqlException sqlexc)
            {
                Console.WriteLine(sqlexc.Message);
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }

            return new List<PhotoObject>();
        }

        /// <summary>
        /// Provede update udaju fotky v databazi
        /// </summary>
        /// <param name="title">titulek</param>
        /// <param name="id">id fotky</param>
        public void UpdatePhotoDetail(string title,int id)
        {
            try
            {
                using (connection = new SqlConnection(ConfigurationManager.ConnectionStrings["amalka"].ToString()))
                {
                    connection.Open();

                    command = new SqlCommand("UPDATE Photos SET update_on=@updated, title=@title WHERE id=@id;", connection);
                    command.Parameters.Add(new SqlParameter("@updated", DateTime.Now));
                    command.Parameters.Add(new SqlParameter("@title", title));
                    command.Parameters.Add(new SqlParameter("@id", id));

                    command.ExecuteNonQuery();
                }
            }
            catch (SqlException sqlexc)
            {
                Console.WriteLine(sqlexc.Message);
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }

        /// <summary>
        /// Smaze fotku z databaze
        /// </summary>
        /// <param name="id">id fotky</param>
        public void DeleteFromDb(int id)
        {
            try
            {
                using (connection = new SqlConnection(ConfigurationManager.ConnectionStrings["amalka"].ToString()))
                {
                    connection.Open();

                    command = new SqlCommand("SELECT file_name FROM Photos WHERE id=@id",connection);
                    command.Parameters.Add(new SqlParameter("@id", id));
                    reader = command.ExecuteReader();
                    reader.Read();
                    string filename = reader["file_name"].ToString();
                    reader.Close();

                    command = new SqlCommand("DELETE FROM Photos WHERE (id = @id);", connection);
                    command.Parameters.Add(new SqlParameter("@id", id));

                    command.ExecuteNonQuery();

                    File.Delete(HttpContext.Current.Server.MapPath(Utils.FotoFolder + @"\" + filename));
                    File.Delete(HttpContext.Current.Server.MapPath(Utils.FotoFolder + @"\" + filename) + Utils.ThumbExtension);
                }
            }
            catch (SqlException sqlexc)
            {
                Console.WriteLine(sqlexc.Message);
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }

    }
}
